import KoaRouter from 'koa-router'
import Config from '@/config/Config'
import verifyToken from '@/middlewares/verifyToken'
import { Models } from '@/common/typings/modle'
import { command } from '@/server/mysql'
import { Account } from '@/common/typings/account'
import { Success } from '@/core/HttpException'
import { commandTotal, formatWhere, getOrderBy, getPaginationStr, getStatusCondition } from '@/common/utils/sql'
const router = new KoaRouter({
  prefix: `${Config.API_PREFIX}v1/system/user`,
})
router.post('/list', verifyToken, async (ctx: Models.Ctx) => {
  const {
    userName,
    status = '1',
    isPagination = true,
    pageSize = 20,
    offset = 0,
    orderField,
    orderDirection,
    onlyTotal = false,
  } = ctx.request.body as any
  // 注意：所有的表都是如此：status为1表示启用，其他表示禁用，一般的，为2或者null表示禁用
  let where = `WHERE 1=1 ${userName ? `AND user_name LIKE '%${userName}%'` : ``} ${getStatusCondition(status)}`
  where = formatWhere(where)
  let total = 0
  let paginationStr = ''
  if (isPagination) {
    total = await commandTotal({ tableName: 'system_user', where })
    if (!onlyTotal) {
      paginationStr = getPaginationStr({ pageSize, offset })
    }
  }
  let list: any = []
  if (!onlyTotal) {
    // 根据orderField 和 orderDirection 进行排序
    const orderBy = getOrderBy({ orderField, orderDirection })
    list = (
      await command(
        `SELECT u.user_name, u.id, u.created_at, u.updated_at, u.gender, u.gender_name, DATE_FORMAT(u.birth, '%Y-%m-%d') as birth, u.mobile, u.address, u.address_detail, u.marital_status, u.marital_status_name, u.email, u.status FROM system_user u ${where} ${orderBy} ${paginationStr};`,
        true,
      )
    ).results as Account.User[]
  }
  throw new Success({
    data: list,
    total,
  })
})
export default router
